<template>
  <common-search :col-layout="{xxl: 6, xl:8, lg: 8, md: 12, sm: 24, xs: 24}" v-model="query" :formItems="formItems" @search="search" @reset="reset"/>
  <div style="margin-bottom: 10px">
    <a-button type="primary" @click="openAdd">
      <template #icon>
        <PlusOutlined />
      </template>
      添加
    </a-button>
    <a-button type="primary" style="margin-left: 10px" @click="exports" :loading="exportLoading">
      <template #icon>
        <ExportOutlined />
      </template>
      导出
    </a-button>
    <a-upload
        name="file"
        :action="action"
        :headers="headers"
        :show-upload-list="false"
        @change="handleChange"
        style="margin-left: 10px"
    >
      <a-button type="primary" :loading="importLoading">
        <uploadOutlined/>
        导入
      </a-button>
    </a-upload>
    <a-button type="primary" style="margin-left: 10px" @click="openTrash">
      <template #icon>
        <DeleteOutlined />
      </template>
      回收站
    </a-button>
  </div>
  <common-table
      :columns="columns"
      :dataSource="dataList"
      v-model:localPagination="page"
      @paginationChange="onPageChange"
      :slots="['action']"
      v-model:loading="loading"
      :scroll="{ x: 'max-content'}"
      :rowKey="(record) => record.id"
  >
    <template #action="{ record }">
      <div class="table-btn">
        <a-button type="link" @click="openEdit(record)">
          <template #icon>
            <EditOutlined />
          </template>
          编辑
        </a-button>
        <a-divider type="vertical" />
        <a-button type="link" @click="openSetDict(record)">
          <template #icon>
            <SettingOutlined />
          </template>
          字典配置
        </a-button>
        <a-divider type="vertical" />
        <a-popconfirm
            title="是否要删除?"
            ok-text="是"
            cancel-text="否"
            @confirm="delOne(record)"
        >
          <a-button type="link">删除</a-button>
        </a-popconfirm>
      </div>
    </template>
  </common-table>
  <add-dictionary :openAdd="addModal" @close="closeAdd"/>
  <data-trash :open-trash="showTrash" @close="closeTrash"/>
  <edit-dictionary :openEdit="editModal" @close="closeEdit" :records="records"/>
  <set-dictionary :openSet="setDraw" :dictId="dictId" @close="closeSet"/>
  <a-modal v-model:open="imports" title="导入">
    <div>
     <span>{{msgs}}</span><br />
     <span>具体详情请 <a :href="href" target="_blank" :download="fileNames">点击下载</a> </span>
    </div>
  </a-modal>
</template>
<script setup>
import CommonSearch from "@/components/commonSearch/index.vue";
import {useSearchTable} from "@/hooks/table/useSearchTable";
import {ref} from "vue";
import {deleteDict, getDictList} from "@/api/system/dict.js";
import CommonTable from "@/components/commonTable/index.vue";
import AddDictionary from "@/components/modal/addDictionary.vue";
import {message} from "ant-design-vue";
import DataTrash from "@/components/modal/dataTrash.vue";
import EditDictionary from "@/components/modal/editDictionary.vue";
import SetDictionary from "@/components/drawer/setDictionary.vue";
import {postFile} from "@utils/service/index.js";
import {getToken, removeToken} from "@utils/storage.js";
import {Logout} from "@/api/user/index.js";
import {Modal} from "ant-design-vue";
const { dataList, query, loading, page, search, reset, onPageChange } = useSearchTable({
  searchAPI: getDictList,
  queryFactory: () => ({
    field:'id,,,dictName,dictCode,description,action',
    order:'desc',
    column:'createTime'
  })
})
const columns = [
  {
    title: '字典名称',
    align: "center",
    dataIndex: 'dictName'
  },
  {
    title: '字典编号',
    align: "center",
    dataIndex: 'dictCode'
  },
  {
    title: '描述',
    align: "center",
    dataIndex: 'description'
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: "center",
  }
]
const formItems = ref([
  {
    label: '字典名称',
    field: 'dictName',
    type: 'input'
  },
  {
    label: '字典编号',
    field: 'dictCode',
    type: 'input'
  }
])
const addModal = ref(false)
const editModal = ref(false)
const showTrash = ref(false)
const setDraw = ref(false)
const imports = ref(false)
const importLoading = ref(false)
const exportLoading = ref(false)
const records = ref({})
const dictId = ref('')
const headers = {
  'X-Access-Token':getToken()
}
const msgs = ref('')
const href = ref('')
const fileNames = ref('')
const action = import.meta.env.VITE_API_BASE_URL + 'sys/dict/importExcel'
/**
 * 新增字典
 */
const openAdd = () => {
  addModal.value = true
}
/**
 * 关闭新增字典
 */
const closeAdd = () => {
  addModal.value = false
  search()
}
/**
 * 修改字典
 */
const openEdit = (record) => {
  editModal.value = true
  records.value = record
}
/**
 * 关闭编辑字典
 */
const closeEdit = () => {
  editModal.value = false
  search()
}
/**
 * 打开回收站
 */
const openTrash = () => {
  showTrash.value = true
}
/**
 * 关闭回收站
 */
const closeTrash = () => {
  showTrash.value = false
  search()
}
/**
 * 删除字典
 * @param record
 */
const delOne = async (record) => {
  try{
    const res = await deleteDict('/sys/dict/delete',{id: record.id})
    message.success('删除成功')
    search()
  }catch (e){
    message.error(e)
  }
}
/**
 * 设置字典
 */
const openSetDict = (record) => {
  setDraw.value = true
  dictId.value = record.id
}
/**
 * 关闭设置字典
 */
const closeSet = () => {
  setDraw.value = false
}
const exports = async () => {
  try{
    exportLoading.value = true
    const res = await postFile('sys/dict/exportXls','get',query.value,'字典.xlsx')
  }catch (e){
    message.error(e)
  }finally {
    exportLoading.value = false
  }
}
const handleChange = (info) => {
  importLoading.value = true
  if (info.file.status === 'done') {
    importLoading.value = false
    if (info.file.response.success) {
      if (info.file.response.code === 201) {
        let { message, result: { msg, fileUrl, fileName } } = info.file.response
        href.value = import.meta.env.VITE_API_BASE_URL + fileUrl
        msgs.value = msg
        fileNames.value = fileName
        imports.value = true
      } else {
        message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
      }
      search()
    } else {
      message.error(`${info.file.name} ${info.file.response.message}.`);
    }
  } else if (info.file.status === 'error') {
    if (info.file.response.status === 500) {
      let data = info.file.response
      const token = getToken()
      if (token && data.message.includes("Token失效")) {
        Modal.confirm({
          title: '登录已过期',
          content: '很抱歉，登录已过期，请重新登录',
          okText: '重新登录',
          onOk: async() => {
            try{
              await Logout({})
              removeToken(import.meta.env.VITE_TOKEN)
              if(import.meta.env.VITE_SSO == 'true'){
                let service = window.location.protocol + '//' + window.location.host + window.location.pathname + window.location.search
                window.location.href = import.meta.env.VITE_CAS_BASE_URL + '/logout?service=' + service
              }else{
                await router.push({path:"/login",replace:true})
              }
            }catch (e){
              message.error(e)
            }
          }
        })
      }
    } else {
      message.error(`文件上传失败: ${info.file.msg} `);
    }
  }
}
</script>
<style scoped>
.table-btn .ant-btn{
  padding: 0;
}
</style>
